<!-- 用户主页 童晓白 2025-07-25	-->
<template>
	<view class="profile-page">
		<!-- 大背景和粒子效果 -->
		<view class="background">
			<view class="bubbles">
				<view class="bubble" v-for="i in 8" :key="i"></view>
			</view>
		</view>
		<view class="particles">
			<view class="particle" v-for="i in 10" :key="i"></view>
		</view>
		<!-- 顶部渐变背景色块 -->
		<view class="profile-top-bg">
			<view class="profile-top-content">
				<view class="avatar-side">
					<view class="avatar-container">
						<image :src="getAvatarUrl(userInfo.avatarUrl)"
							alt="用户头像"
							class="avatar-main"
							@error="handleAvatarError" />
						<!-- 换头像按钮 - 仅本人可见 -->
						<view v-if="isCurrentUser" class="avatar-change-btn" @tap="uploadAvatar">
							<text class="change-icon">更换</text>
						</view>
					</view>
				</view>
				<view class="user-info-side">
					<view class="user-main-row">
						<text class="nickname-main">{{ userInfo.nickname || '加载中...' }}</text>
						<text class="credit-score" @tap="goToReputationScore">信誉分：{{ userInfo.creditScore || 80 }} ▶</text>
					</view>
					<!-- 余额显示 - 仅本人可见 -->
					<view class="balance-row" v-if="isCurrentUser">
						<text class="balance-label">账户余额</text>
						<text class="balance-amount">¥{{ userBalance.toFixed(2) }}</text>
						<text class="recharge-btn" @tap="goToRecharge">充值 ▶</text>
					</view>
					<view class="user-id-row">
						<text class="user-id">ID: {{ userInfo.uid || '---' }}</text>
					</view>
					<!-- 这里插入铭牌展示 -->
					<!-- 铭牌仓库区优化：仅本人可操作 -->
					<view class="show-badges-row" v-if="showBadges.length">
						<view class="show-badge-list">
							<image
								v-for="badge in showBadges"
								:key="badge.id"
								:src="getBadgeImage(badge)"
								:alt="getBadgeTitle(badge)"
								class="show-badge-img"
								:title="getBadgeTitle(badge)"
								@tap="goToBadgeDetail(badge)"
							/>
							<!-- 仅本人主页显示操作按钮（如悬挂/取消悬挂） -->
							<template v-if="isCurrentUser">
								<!-- 这里可加悬挂/取消悬挂按钮，参考网页端逻辑 -->
							</template>
						</view>
					</view>
				</view>
				<!-- 右上角三条杠按钮，仅本人主页显示 -->
				<view class="menu-btn" @tap="goToSetting" v-if="isCurrentUser">
					<view class="menu-icon">
						<view class="bar"></view>
						<view class="bar"></view>
						<view class="bar"></view>
					</view>
				</view>
			</view>

			<!-- 简介/签名 -->
			<view class="profile-bio-row">
				<text class="bio"> 所属机构：
					<text v-if="userInfo.orgName && userInfo.creditCode" 
						class="org-link" 
						@click="goToOrganization(userInfo.creditCode)">
						{{ userInfo.orgName }}
					</text>
					<text v-else>{{ userInfo.orgName || '无' }}</text>
					<text v-if="userInfo.orgPosition" style="margin-left:8px;">（{{ userInfo.orgPosition }}）</text>
				</text>
			</view>
			<view class="profile-bio-row">
				<text class="bio"> 个性签名：{{ userInfo.signature || '这个人很懒，什么都没留下' }}</text>
			</view>
		</view>
		<!-- 极简紧凑卡片组内容区 -->
		<view class="profile-content-card">
			<view class="card-group">
				<view class="card card-top">
					<view class="profile-card-title">功能</view>
					<view class="profile-list">
						<view class="profile-list-item" @tap="goToSkillTree">
							<text class="profile-list-title">技能树</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
						<view class="profile-list-item" @tap="goToBadges">
							<text class="profile-list-title">铭牌仓库</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
						<view class="profile-list-item" @tap="goToShop">
							<text class="profile-list-title">装饰商城</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
						<view class="profile-list-item" @tap="goToWarehouse">
							<text class="profile-list-title">装饰仓库</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
					</view>
				</view>
				<!-- 仅本人主页显示设置反馈区 -->
				<view class="card card-bottom" v-if="isCurrentUser">
					<view class="profile-card-title">设置反馈</view>
					<view class="profile-list">
						<view class="profile-list-item" @click="goToDeviceManagement">
							<text class="profile-list-title">设备管理</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
						<view class="profile-list-item" @click="goToAbout">
							<text class="profile-list-title">关于我们</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
						<view class="profile-list-item" @click="goToUpdate">
							<text class="profile-list-title">版本更新</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
						<view class="profile-list-item" @click="goToFeedback">
							<text class="profile-list-title">意见反馈</text>
							<text class="profile-list-arrow">&gt;</text>
						</view>
					</view>
				</view>
				<!-- 他人主页可选：可加只读卡片或留空 -->
			</view>
		</view>
	</view>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { useUserStore } from '@/store/user';
import { onShow } from '@dcloudio/uni-app'

import { getBadgeNameByAssociation } from '@/utils/skillUtils';
import DarkModeButton from '@/components/darkmodelbutton.vue';
import { getAvatarUrl, getOrgAvatarUrl } from '@/utils/imageUtils.js';

const userStore = useUserStore();

// 主题切换
const theme = ref('light');
const isNight = ref(false);

const handleDarkModeChange = (isDarkMode) => {
	theme.value = isDarkMode ? 'dark' : 'light';
	document.documentElement.setAttribute('data-theme', theme.value);
};

// 用户信息
const userInfo = reactive({
	uid: '',
	nickname: '',
	avatarUrl: '',
	signature: '',
	creditScore: 0,
	phone: '',
	email: '',
	organization: '',
	title: '',
	orgName: '',
	orgAvatarUrl: '',
	orgPosition: ''
});

// 用户余额
const userBalance = ref(0);

// 判断是否是当前登录用户
const isCurrentUser = computed(() => {
  // 只要 userInfo.uid 和 userStore.profile.uid 相等就是本人
  // 添加安全检查，防止 userStore.profile 为 undefined
  return userInfo.uid && userStore.profile && userInfo.uid === userStore.profile.uid;
});

// 页面加载时获取用户信息
onMounted(async () => {
	const routeUid = uni.getStorageSync('routeUid') || '';
	const viewOtherUser = uni.getStorageSync('viewOtherUser');
	// 添加安全检查，防止 userStore.profile 为 undefined
	const myUid = userStore.profile?.uid;
	let targetUid = routeUid || myUid;
	
	// 如果设置了查看其他用户标记，则查看指定用户
	if (viewOtherUser === 'true' && routeUid && routeUid !== myUid) {
		// 查看其他用户，调用 /user/info
		try {
			const token = uni.getStorageSync('accessToken');
			const res = await uni.request({
				url: `${NETWORK_CONFIG.API_BASE_URL}/user/info`,
				method: 'POST',
				data: { uid: targetUid },
				header: { 'Access-Token': `Bearer ${token}` }
			});
			Object.assign(userInfo, res.data);
			// 设置查看其他用户状态
			// viewOtherUser 是从存储中读取的字符串，不需要设置 .value
		} catch (error) {
			console.error('加载他人用户信息失败', error);
		}
	} else if (!routeUid || routeUid === myUid) {
		// 是自己，调用 /user/me
		await userStore.fetchUserProfile();
		// 清除 routeUid，避免下次误用
		uni.removeStorageSync('routeUid');
		uni.removeStorageSync('viewOtherUser');
	} else {
		// 不是自己，调用 /user/info
		try {
			const token = uni.getStorageSync('accessToken');
			const res = await uni.request({
				url: `${NETWORK_CONFIG.API_BASE_URL}/user/info`,
				method: 'POST',
				data: { uid: targetUid },
				header: { 'Access-Token': `Bearer ${token}` }
			});
			Object.assign(userInfo, res.data);
		} catch (error) {
			console.error('加载他人用户信息失败', error);
		}
		// 不要清除routeUid，因为跳转函数还需要使用它
		// uni.removeStorageSync('routeUid');
	}
	// 继续加载徽章等其它信息
	await loadBadges(targetUid);
	await fetchUserBadges(targetUid); // 获取徽章数据
	await fetchShowBadges(targetUid); // 获取展示徽章
	
	// 如果是当前用户，加载余额信息
	if (isCurrentUser.value) {
		await loadUserBalance();
	}
});

onShow(async () => {
  // 先清空 userInfo，防止残留他人信息
  Object.keys(userInfo).forEach(key => userInfo[key] = '')

  const routeUid = uni.getStorageSync('routeUid')
  const viewOtherUser = uni.getStorageSync('viewOtherUser')
  // 添加安全检查，防止 userStore.profile 为 undefined
  const myUid = userStore.profile?.uid
  
  console.log('个人页面 onShow - routeUid:', routeUid, 'viewOtherUser:', viewOtherUser, 'myUid:', myUid)
  console.log('当前 userStore.profile.uid:', userStore.profile?.uid)
  
  // 根据是否有明确的"查看其他用户"标记来决定显示逻辑
  if (viewOtherUser === 'true' && routeUid && routeUid !== myUid) {
    // 有明确标记要查看其他用户，显示其他用户信息
    console.log('显示其他用户信息，routeUid:', routeUid)
    
    // 清除标记，避免下次误判
    uni.removeStorageSync('viewOtherUser')
    
    // 拉取他人信息
    try {
      const token = uni.getStorageSync('accessToken')
      const res = await uni.request({
        url: `${NETWORK_CONFIG.API_BASE_URL}/user/info`,
        method: 'POST',
        data: { uid: routeUid },
        header: { 'Access-Token': `Bearer ${token}` }
      })
      
      console.log('获取他人信息返回：', res)
      
      const userData = res.data
      if (userData && userData.uid) {
        // 使用 Object.assign 确保响应式更新
        Object.assign(userInfo, {
          uid: userData.uid,
          nickname: userData.nickname,
          avatarUrl: userData.avatarUrl,
          signature: userData.signature,
          creditScore: userData.creditScore,
          adCode: userData.adCode,
          creditCode: userData.creditCode,
          executive: userData.executive,
          releaseTime: userData.releaseTime,
          orgName: userData.orgName,
          orgAvatarUrl: userData.orgAvatarUrl,
          orgPosition: userData.orgPosition
        })
        
        console.log('更新后的他人 userInfo：', userInfo)
      }
    } catch (error) {
      console.error('加载他人用户信息失败', error)
      uni.showToast({ title: '获取他人信息失败', icon: 'none' })
    }

    // 加载铭牌信息（使用其他用户ID）
    await loadBadges(routeUid)
    await fetchUserBadges(routeUid)
    await fetchShowBadges(routeUid)
  } else {
    // 没有明确标记或标记为false，显示当前用户信息
    // 清除所有相关缓存
    uni.removeStorageSync('routeUid')
    uni.removeStorageSync('viewOtherUser')
    console.log('显示当前用户信息')
    
    // 先尝试从store获取最新信息，如果store中有数据且是最新的
    if (userStore.profile && userStore.profile.uid) {
      console.log('从store获取用户信息：', userStore.profile)
      Object.assign(userInfo, {
        uid: userStore.profile.uid,
        nickname: userStore.profile.nickname,
        avatarUrl: userStore.profile.avatarUrl,
        signature: userStore.profile.signature,
        creditScore: userStore.profile.creditScore,
        adCode: userStore.profile.adCode,
        creditCode: userStore.profile.creditCode,
        executive: userStore.profile.executive,
        releaseTime: userStore.profile.releaseTime,
        phone: userStore.profile.phone,
        email: userStore.profile.email,
        password: userStore.profile.password,
        idCard: userStore.profile.idCard,
        name: userStore.profile.name,
        gender: userStore.profile.gender,
        orgName: userStore.profile.orgName,
        orgAvatarUrl: userStore.profile.orgAvatarUrl,
        orgPosition: userStore.profile.orgPosition
      })
      console.log('从store更新后的 userInfo：', userInfo)
    }
    
    // 强制拉取自己的最新信息
    const token = uni.getStorageSync('accessToken')
    try {
      const res = await uni.request({
		url: `${NETWORK_CONFIG.API_BASE_URL}/user/me`,
        method: 'POST',
        header: { 'Access-Token': `Bearer ${token}` }
      })
      
      console.log('获取本人信息返回：', res)
      
      // 根据你的接口返回，数据直接在 res.data 中
      const userData = res.data
      console.log('解析后的用户数据：', userData)
      
      if (userData && userData.uid) {
        // 使用 Object.assign 确保响应式更新
        Object.assign(userInfo, {
          uid: userData.uid,
          nickname: userData.nickname,
          avatarUrl: userData.avatarUrl,
          signature: userData.signature,
          creditScore: userData.creditScore,
          adCode: userData.adCode,
          creditCode: userData.creditCode,
          executive: userData.executive,
          releaseTime: userData.releaseTime,
          phone: userData.phone,
          email: userData.email,
          password: userData.password,
          idCard: userData.idCard,
          name: userData.name,
          gender: userData.gender,
          orgName: userData.orgName,
          orgAvatarUrl: userData.orgAvatarUrl,
          orgPosition: userData.orgPosition
        })
        
        // 同步更新 userStore.profile，确保显示当前用户信息
        Object.assign(userStore.profile, userData)
        
        console.log('更新后的 userInfo：', userInfo)
        console.log('更新后的 userStore.profile：', userStore.profile)
      } else {
        console.error('接口返回数据格式异常：', userData)
        uni.showToast({ title: '获取用户信息失败', icon: 'none' })
      }
    } catch (e) {
      console.error('获取本人信息失败', e)
      uni.showToast({ title: '网络请求失败', icon: 'none' })
    }

    // 加载铭牌信息（使用当前用户ID）
    await loadBadges(myUid)
    await fetchUserBadges(myUid)
    await fetchShowBadges(myUid)
    
    // 加载余额信息
    await loadUserBalance()
  }
  
  // 监听任务相关更新事件
  uni.$on('task-related-update', (data) => {
    console.log('🔄 个人页面收到任务相关更新事件:', data);
    // 刷新用户信息（使用当前显示的用户ID）
    const currentUid = routeUid || myUid;
    loadUserInfo(currentUid);
    loadBadges(currentUid);
    fetchUserBadges(currentUid);
    fetchShowBadges(currentUid);
  });
  
  // 监听查看其他用户个人主页事件
  uni.$on('viewUserProfile', (data) => {
    console.log('🔄 个人页面收到查看用户个人主页事件:', data);
    if (data && data.uid) {
      // 切换到查看指定用户
      routeUid.value = data.uid;
      viewOtherUser.value = true;
      // 重新加载用户信息
      loadUserInfo(data.uid);
      loadBadges(data.uid);
      fetchUserBadges(data.uid);
      fetchShowBadges(data.uid);
    }
  });
  
  // 监听用户信息更新事件
  uni.$on('user-profile-updated', (data) => {
    console.log('🔄 个人页面收到用户信息更新事件:', data);
    // 如果显示的是当前用户信息，则更新显示
    if (!routeUid || routeUid === myUid) {
      // 从store获取最新信息
      if (userStore.profile && userStore.profile.uid) {
        Object.assign(userInfo, {
          uid: userStore.profile.uid,
          nickname: userStore.profile.nickname,
          avatarUrl: userStore.profile.avatarUrl,
          signature: userStore.profile.signature,
          creditScore: userStore.profile.creditScore,
          adCode: userStore.profile.adCode,
          creditCode: userStore.profile.creditCode,
          executive: userStore.profile.executive,
          releaseTime: userStore.profile.releaseTime,
          phone: userStore.profile.phone,
          email: userStore.profile.email,
          password: userStore.profile.password,
          idCard: userStore.profile.idCard,
          name: userStore.profile.name,
          gender: userStore.profile.gender,
          orgName: userStore.profile.orgName,
          orgAvatarUrl: userStore.profile.orgAvatarUrl,
          orgPosition: userStore.profile.orgPosition
        });
        console.log('🔄 个人页面已更新用户信息:', userInfo);
      }
    }
  });
})

// 加载用户信息
const loadUserInfo = async (uid) => {
	try {
		const token = uni.getStorageSync('accessToken');

		// 如果是当前用户，使用 /user/me 接口获取完整信息
		if (uid === userStore.profile.uid) {
			await userStore.fetchUserProfile(); // 直接调用 store 的方法
		} else {
			// 如果是查看其他用户，使用 /user/info 接口获取公开信息
			const res = await uni.request({
				url: `${NETWORK_CONFIG.API_BASE_URL}/user/info`,
				method: 'POST',
				data: { uid },
				header: { 'Access-Token': `Bearer ${token}` }
			});
			Object.assign(userInfo, res.data);
		}
	} catch (error) {
		console.error('获取用户信息失败', error);
	}
};

// 上传头像
const uploadAvatar = async () => {
	// uni-app 选择图片
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			const tempFilePath = res.tempFilePaths[0];

	try {
		const token = uni.getStorageSync('accessToken');
				const uploadRes = await uni.uploadFile({
			url: `${NETWORK_CONFIG.API_BASE_URL}/user/upload-avatar`,
					filePath: tempFilePath,
					name: 'file',
			header: {
				'Access-Token': `Bearer ${token}`
			}
		});
				
				const data = JSON.parse(uploadRes.data);
				userStore.profile.avatarUrl = data.filePath;
				userInfo.avatarUrl = data.filePath;
				
				uni.showToast({
					title: '头像上传成功',
					icon: 'success'
				});
	} catch (error) {
		console.error('上传头像失败', error);
				uni.showToast({
					title: '头像上传失败',
					icon: 'none'
				});
			}
		},
		fail: (err) => {
			console.error('选择图片失败', err);
		}
	});
};

// 处理头像加载错误
const handleAvatarError = () => {
	console.log('头像加载失败，使用默认头像');
	// 可以设置默认头像
};

// 复制文本
const copyText = (text) => {
	if (!text) return;

	// uni-app 复制到剪贴板
	uni.setClipboardData({
		data: text,
		success: () => {
			uni.showToast({
				title: '已复制到剪贴板',
				icon: 'success'
			});
		},
		fail: (err) => {
			console.error('复制失败', err);
			uni.showToast({
				title: '复制失败',
				icon: 'none'
			});
		}
		});
};

// 跳转到机构页面
const goToOrganization = (creditCode) => {
	const targetCreditCode = creditCode || userStore.profile.creditCode;
	console.log('🔍 跳转企业页面 - 传递的creditCode:', targetCreditCode);
	console.log('🔍 当前用户信息:', userStore.profile);
	if (targetCreditCode) {
		uni.navigateTo({
			url: `/pages/business/organization/index?id=${encodeURIComponent(targetCreditCode)}`,
			fail: (err) => {
				console.error('跳转到机构页面失败:', err);
				uni.showToast({
					title: '页面跳转失败',
					icon: 'none'
				});
			}
		});
	} else {
		uni.showToast({
			title: '该用户未绑定机构',
			icon: 'none'
		});
	}
};

// 跳转到技能树页面
const goToSkillTree = () => {
	const profileUid = uni.getStorageSync('routeUid') || userStore.profile.uid;
	console.log('=== 技能树跳转调试信息 ===');
	console.log('routeUid:', uni.getStorageSync('routeUid'));
	console.log('userStore.profile.uid:', userStore.profile.uid);
	console.log('最终使用的profileUid:', profileUid);
	console.log('跳转URL:', `/pages/skill-tree/index?uid=${profileUid}`);
	console.log('========================');
	
	uni.navigateTo({
		url: `/pages/skill-tree/index?uid=${profileUid}`,
		fail: (err) => {
			console.error('跳转到技能树页面失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};
const goToUpdate = () => {
	uni.navigateTo({
		url: '/pages/update/index',
	});
};
const goToFeedback = () => {
	uni.navigateTo({
		url: '/pages/feedback/index',
	});
};
const goToAbout = () => {
	uni.navigateTo({
		url: '/pages/aboutour/index',
	});
};

// 跳转到信誉分页面
const goToReputationScore = () => {
	console.log('开始跳转到信誉分页面...')
	uni.navigateTo({
		url: '/pages/reputationscore/index',
		success: () => {
			console.log('跳转到信誉分页面成功')
		},
		fail: (err) => {
			console.error('跳转到信誉分页面失败:', err)
			uni.showToast({
				title: '页面跳转失败: ' + (err.errMsg || '未知错误'),
				icon: 'none',
				duration: 3000
			})
		}
	})
}
// 徽章相关
const hangedBadges = ref([]);
const invisibleBadges = ref([]);
const showMoreBadges = ref(false);

const logout = () => {
	uni.removeStorageSync('accessToken');
	uni.reLaunch({
		url: '/pages/auth/login/index',
		fail: (err) => {
			console.error('跳转到登录页面失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};

// 加载徽章
const loadBadges = async (uid) => {
	try {
		const token = uni.getStorageSync('accessToken');

		// 如果是当前用户，加载悬挂的和未悬挂的徽章
		if (isCurrentUser.value) {
			// 加载悬挂的徽章
			const hangedRes = await uni.request({
				url: `${NETWORK_CONFIG.API_BASE_URL}/badge/user-hanged-badges?uid=${uid}`,
				method: 'GET',
				header: { 'Access-Token': `Bearer ${token}` }
			});
			hangedBadges.value = hangedRes.data || [];

			// 加载未悬挂的徽章
			const invisibleRes = await uni.request({
				url: `${NETWORK_CONFIG.API_BASE_URL}/badge/top-level-badges`,
				method: 'GET',
				header: { 'Access-Token': `Bearer ${token}` }
			});
			invisibleBadges.value = invisibleRes.data || [];
		} else {
			// 如果查看其他用户的主页，只加载已悬挂的徽章
			const response = await uni.request({
				url: `${NETWORK_CONFIG.API_BASE_URL}/badge/user-hanged-badges?uid=${uid}`,
				method: 'GET',
				header: { 'Access-Token': `Bearer ${token}` }
			});
			hangedBadges.value = response.data || [];
		}
	} catch (error) {
		console.error('加载徽章失败', error);
	}
};

// 获取徽章标题
const getBadgeTitle = (badge) => {
	// 使用skillUtils中的函数获取徽章名称
	const badgeName = getBadgeNameByAssociation(badge.association || '000000');

	// 如果徽章有评价，添加到标题
	if (badge.evaluation) {
		return `${badgeName}: ${badge.evaluation}`;
	}

	return badgeName;
};

// 获取用户贡献百分比
const getUserContribution = (badge) => {
	// 主页用户uid
	const profileUid = Number(uni.getStorageSync('routeUid') || userStore.profile.uid);
	const contributor = badge.contributors?.find(c => c.uid === profileUid);
	return contributor?.percentage || 0;
};

// 切换徽章状态（悬挂/隐藏）
const toggleBadgeStatus = async (badge, newStatus) => {
	if (!isCurrentUser.value) return;

	try {
		const token = uni.getStorageSync('accessToken');
		const res5 = await uni.request({
			url: `${NETWORK_CONFIG.API_BASE_URL}/badge/changestatus`,
			method: 'PATCH',
			header: { 'Access-Token': `Bearer ${token}` },
			data: {
				badgeId: badge.id,
				status: newStatus
			}
		});

		// 更新本地数据
		if (newStatus === 0) {
			// 从悬挂变为隐藏
			hangedBadges.value = hangedBadges.value.filter(b => b.id !== badge.id);
			invisibleBadges.value.push(badge);
		} else {
			// 从隐藏变为悬挂
			invisibleBadges.value = invisibleBadges.value.filter(b => b.id !== badge.id);
			hangedBadges.value.push(badge);
		}

		// 更新徽章的状态
		const badgeIndex = newStatus === 0
			? hangedBadges.value.findIndex(b => b.id === badge.id)
			: invisibleBadges.value.findIndex(b => b.id === badge.id);

		if (badgeIndex !== -1) {
			const updatedBadge = newStatus === 0
				? hangedBadges.value[badgeIndex]
				: invisibleBadges.value[badgeIndex];

			const currentUid = Number(userStore.profile.uid);
			const contributorIndex = updatedBadge.contributors.findIndex(c => c.uid === currentUid);

			if (contributorIndex !== -1) {
				updatedBadge.contributors[contributorIndex].status = newStatus;
			}
		}
	} catch (error) {
		console.error('更新徽章状态失败', error);
	}
};

// 在<script setup>中添加方法
const goToAssociation = (badge) => {
	const uid = uni.getStorageSync('routeUid') || userStore.profile.uid;
	uni.navigateTo({
		url: `/pages/skill-tree/association/index?contributorId=${uid}&badges=${badge.association}`,
		fail: (err) => {
			console.error('跳转到协会页面失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};

const getRandomBadgeImage = () => {
	const badgeImages = [
		'/images/badge1.png',
		'/images/badge2.png',
		'/images/badge3.png',
		'/images/badge4.png',
		'/images/badge5.png'
	];
	const randomIndex = Math.floor(Math.random() * badgeImages.length);
	return badgeImages[randomIndex];
};

const goToSetting = () => {
	uni.navigateTo({
		url: '/pages/setting/index',
		fail: (err) => {
			console.error('跳转到设置页面失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};


// 跳转到铭牌仓库页面
const goToBadges = () => {
	// 添加安全检查，防止 userStore.profile 为 undefined
	const profileUid = uni.getStorageSync('routeUid') || userStore.profile?.uid;
	
	console.log('=== 铭牌仓库跳转调试信息 ===');
	console.log('routeUid:', uni.getStorageSync('routeUid'));
	console.log('userStore.profile.uid:', userStore.profile?.uid);
	console.log('最终使用的profileUid:', profileUid);
	console.log('是否查看自己:', profileUid === userStore.profile?.uid);
	console.log('========================');
	
	// 如果不是查看自己的主页，需要传递uid参数
	if (profileUid !== userStore.profile?.uid) {
		console.log('跳转URL:', `/pages/badges/index?uid=${profileUid}`);
		uni.navigateTo({
			url: `/pages/badges/index?uid=${profileUid}`,
			fail: (err) => {
				uni.showToast({ title: '页面跳转失败', icon: 'none' });
			}
		});
	} else {
		// 查看自己的，不需要uid参数
		console.log('跳转URL:', '/pages/badges/index');
		uni.navigateTo({
			url: '/pages/badges/index',
			fail: (err) => {
				uni.showToast({ title: '页面跳转失败', icon: 'none' });
			}
		});
	}
};





const userBadges = ref([]);

// 获取用户所有徽章
const fetchUserBadges = async (uid) => {
	try {
		const token = uni.getStorageSync('accessToken');
		const res = await uni.request({
			url: `${NETWORK_CONFIG.API_BASE_URL}/badge/user-badges?uid=${uid}`,
			method: 'GET',
			header: { 'Access-Token': `Bearer ${token}` }
		});
		userBadges.value = res.data || [];
	} catch (e) {
		console.error('获取用户徽章失败', e);
	}
};

const showBadges = ref([]);

const fetchShowBadges = async (uid) => {
	try {
		const token = uni.getStorageSync('accessToken');
		const res = await uni.request({
			url: `${NETWORK_CONFIG.API_BASE_URL}/badge/user-badges?uid=${uid}`,
			method: 'GET',
			header: { 'Access-Token': `Bearer ${token}` }
		});
		// 只保留contributors中当前用户status为1的徽章
		const myUid = Number(uid);
		showBadges.value = (res.data || []).filter(badge =>
			Array.isArray(badge.contributors) &&
			badge.contributors.some(c => c.uid === myUid && c.status === 1)
		);
	} catch (e) {
		console.error('获取展示徽章失败', e);
	}
};

onMounted(async () => {
	const uid = uni.getStorageSync('routeUid') || userStore.profile.uid;
	if (uid) {
		await fetchShowBadges(uid);
	}
});

// 清理事件监听器
onUnmounted(() => {
  uni.$off('task-related-update');
  uni.$off('user-profile-updated');
  uni.$off('viewUserProfile');
});

// 获取徽章图片（可根据 association 或 level 映射图片）
const getBadgeImage = (badge) => {
	const badgeImages = [
		'/images/badge1.png',
		'/images/badge2.png',
		'/images/badge3.png',
		'/images/badge4.png',
		'/images/badge5.png'
	];
	return badgeImages[badge.level % badgeImages.length];
};

const goToBadgeDetail = (badge) => {
  const profileUid = uni.getStorageSync('routeUid') || userStore.profile.uid;
  
  console.log('=== 徽章详情跳转调试信息 ===');
  console.log('routeUid:', uni.getStorageSync('routeUid'));
  console.log('userStore.profile.uid:', userStore.profile.uid);
  console.log('最终使用的profileUid:', profileUid);
  console.log('徽章association:', badge.association);
  console.log('跳转URL:', `/pages/skill-tree/association/index?contributorId=${profileUid}&badges=${badge.association}`);
  console.log('========================');
  
  uni.navigateTo({
    url: `/pages/skill-tree/association/index?contributorId=${profileUid}&badges=${badge.association}`,
		fail: (err) => {
			uni.showToast({ title: '页面跳转失败', icon: 'none' });
		}
	});
};

// 加载用户余额
const loadUserBalance = async () => {
	try {
		const token = uni.getStorageSync('accessToken');
		const userId = userStore.profile?.uid;
		
		if (!userId) {
			console.error('用户ID不存在');
			return;
		}
		
		const res = await uni.request({
			url: `${NETWORK_CONFIG.API_BASE_URL}/api/recharge/account`,
			method: 'GET',
			data: { userId: userId },
			header: { 'Access-Token': `Bearer ${token}` }
		});
		
		if (res.data && res.data.success) {
			userBalance.value = parseFloat(res.data.data.balance) || 0;
			console.log('用户余额加载成功:', userBalance.value);
		} else {
			console.error('获取余额失败:', res.data?.message);
		}
	} catch (error) {
		console.error('加载用户余额失败:', error);
	}
};

// 跳转到充值页面
const goToRecharge = () => {
	const userId = userStore.profile?.uid;
	if (!userId) {
		uni.showToast({
			title: '用户信息异常',
			icon: 'none'
		});
		return;
	}
	
	uni.navigateTo({
		url: `/pages/recharge/index?userId=${userId}`,
		fail: (err) => {
			console.error('跳转到充值页面失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};

// 跳转到装饰商城
const goToShop = () => {
	const userId = userStore.profile?.uid;
	if (!userId) {
		uni.showToast({
			title: '用户信息异常',
			icon: 'none'
		});
		return;
	}
	
	uni.navigateTo({
		url: `/pages/shop/index?userId=${userId}`,
		fail: (err) => {
			console.error('跳转到装饰商城失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};

// 跳转到装饰仓库
const goToWarehouse = () => {
	const userId = userStore.profile?.uid;
	if (!userId) {
		uni.showToast({
			title: '用户信息异常',
			icon: 'none'
		});
		return;
	}
	
	uni.navigateTo({
		url: `/pages/warehouse/index?userId=${userId}`,
		fail: (err) => {
			console.error('跳转到装饰仓库失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};

// 跳转到设备管理
const goToDeviceManagement = () => {
	uni.navigateTo({
		url: '/pages/device-management/index',
		fail: (err) => {
			console.error('跳转到设备管理失败:', err);
			uni.showToast({
				title: '页面跳转失败',
				icon: 'none'
			});
		}
	});
};
</script>

<style scoped>
.profile-page {
  margin: 0;
  padding: 0;
  min-height: 100vh;
  font-family: "Microsoft YaHei", "微软雅黑", sans-serif;
  background: #f5f6fa;
  color: #222;
  display: flex;
  flex-direction: column;
  align-items: center;
  overflow-y: auto;
  position: relative;
}
.avatar-container {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 3px solid #eee;
  overflow: hidden;
  margin-right: 16px;
  margin-top: 12px;
  padding: 0;
  position: relative;
}
.avatar-main {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  background: #eee;
  display: block;
}

.avatar-change-btn {
	position: absolute;
	bottom: 0;
	right: 0;
	width: 28px;
	height: 28px;
	background: #007AFF;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	cursor: pointer;
	box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
	transition: all 0.2s ease;
	border: 2px solid white;
}

.avatar-change-btn:hover {
	background: #0056CC;
	transform: scale(1.1);
}

.change-icon {
	font-size: 12px;
	color: white;
	font-weight: 500;
}
.nickname-main {
  font-size: 1.5rem;
  font-weight: bold;
  color: #fff;
  line-height: 1.3;
  letter-spacing: 0.5px;
  margin-left: 12px;
  margin-bottom: 0;
  margin-top: 0;
  max-width: 120px; /* 你可以根据实际宽度调整 */
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex-shrink: 1;   /* 允许缩短 */
}
.user-id {
  font-size: 0.85rem;
  color: rgba(255,255,255,0.75);
  margin-top: 2px;
  margin-left: 12px;
  font-family: 'Consolas', 'Menlo', 'Monaco', 'Courier New', monospace;
  letter-spacing: 0.5px;
  font-weight: 500;
  text-shadow: 0 1px 2px rgba(0,0,0,0.08);
}
.profile-top-bg {
  width: 100%;
  background: #4a90e2;
  padding: 12px 0 8px 0;
  min-height: unset;      /* 不要强制最小高度 */
}
.profile-top-content {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  padding: 0 16px;
  margin-top: 0;          /* 去掉多余的margin */
  position: relative;
}

.avatar-side {
  display: flex;
  align-items: flex-start;
  margin-top: 0;          /* 头像不再下移 */
}

.avatar-container {
  width: 65px;            
  height: 65px;
  margin-right: 12px;
}

.user-info-side {
  margin-top: 0;
}

.user-main-row {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 0;
  margin-top: 0;
  max-width: 100%;
}
.profile-bio-row {
  margin-top: 10px;       /* 签名与上方间距缩小 */
  padding-left: 16px;
}
.profile-bio-row .bio {
  color: rgba(255,255,255,0.85);
  font-size: 1rem;
  font-style: italic;
  font-weight: 400;
  text-shadow: 0 1px 2px rgba(0,0,0,0.10);
  letter-spacing: 0.5px;
  line-height: 1.5;
}

.org-link {
  color: #007AFF;
  text-decoration: underline;
  cursor: pointer;
  transition: color 0.2s;
}

.org-link:hover {
  color: #0056CC;
}
.menu-btn {
  position: absolute;
  top: 5px;
  right: 10px;
  width: 40px;
  height: 40px;
  background: #888;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  cursor: pointer;
}
.menu-icon {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 22px;
  width: 22px;
  gap: 4px;
}
.menu-icon .bar {
  width: 18px;
  height: 3px;
  background: #fff;
  border-radius: 2px;
  display: block;
}
.profile-content-card {
  width: 100%;
  margin: 0;
  background: transparent;
  padding: 0 0 32px 0;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.card-group {
  width: 100%;
  background: #f8f9fa;
  border-radius: 18px;
  overflow: hidden;
  margin: 0;
  position: relative;
}
.card {
  width: 100%;
  padding: 0 0;
  border-bottom: 1px solid #f5f5f5;
  background: #f8f9fa;
  margin: 0 0 1px 0;
  border-radius: 0;
}
.card-top {
  border-top-left-radius: 18px;
  border-top-right-radius: 18px;
}
.card-bottom {
  border-bottom-left-radius: 18px;
  border-bottom-right-radius: 18px;
  border-bottom: none;
}
.profile-list {
  list-style: none;
  margin: 0;
  padding: 0;
}
.profile-list-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 18px 16px;
  border-bottom: 1px solid #f5f5f5;
  font-size: 16px;
  color: #222;
  background: #fff;
  cursor: pointer;
  font-family: 'PingFang SC', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
  font-weight: 400;
  position: relative;
  overflow: hidden;
}
.profile-list-title {
  color: #222;
  font-size: 16px;
  font-family: 'PingFang SC', 'Microsoft YaHei', '微软雅黑', Arial, sans-serif;
  font-weight: 400;
}
.profile-list-arrow {
  color: #bbb;
  font-size: 20px;
  margin-left: 8px;
}
.profile-card-title {
  font-size: 14px;
  font-weight: 500;
  color: #888;
  padding: 12px 0 8px 16px;
  letter-spacing: 0.5px;
  text-align: left;
  background: #f8f9fa;
}
.credit-score {
  background: #fff3cd;
  color: #856404;
  border-radius: 8px;
  padding: 1px 7px;
  font-size: 0.85rem;
  margin-left: 10px;
  font-weight: 500;
  vertical-align: middle;
  display: flex;
  align-items: center;
  height: 1.5rem;
  margin-bottom: 0;
  margin-top: 0;
  flex-shrink: 0;   /* 不允许被压缩 */
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.credit-score:hover {
  background: #ffeaa7;
  border-color: #fdcb6e;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(133, 100, 4, 0.15);
}

.credit-score:active {
  transform: translateY(0);
  box-shadow: 0 1px 4px rgba(133, 100, 4, 0.2);
}

.badge-row {
  margin-top: 8px;
  display: flex;
  align-items: center;
}
.badge-list {
  display: flex;
  align-items: center;
  gap: 6px;
}
.badge-img {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: 1px solid #eee;
  background: #fff;
  object-fit: cover;
  cursor: pointer;
  transition: transform 0.2s;
}
.badge-img:hover {
  transform: scale(1.1);
}
.badge-more {
  color: #888;
  font-size: 1.1rem;
  margin-left: 4px;
  cursor: pointer;
}
.hanged-badges-row {
  margin: 10px 0 0 0;
  width: 100%;
  display: flex;
  align-items: center;
  padding-left: 2px;
}

.hanged-badge-list {
  display: flex;
  flex-wrap: wrap;      /* 支持自动换行 */
  align-items: center;
  margin-left: 12px;
  gap: 8px;             /* 徽章间距 */
  min-height: 36px;     /* 保证高度一致 */
}

.hanged-badge-img {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: 2px solid #fff;
  background: #f8f9fa;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  cursor: pointer;
  transition: transform 0.18s;
}
.hanged-badge-img:hover {
  transform: scale(1.12);
}
.show-badges-row {
  margin: 10px 0 0 0;
  width: 100%;
  display: flex;
  align-items: center;
  padding-left: 2px;
}
.show-badge-list {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-left: 12px;
  gap: 8px;
  min-height: 36px;
}
.show-badge-img {
  width: 32px;
  height: 32px;
  border-radius: 8px;
  border: 2px solid #fff;
  background: #f8f9fa;
  object-fit: cover;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
  cursor: pointer;
  transition: transform 0.18s;
}
.show-badge-img:hover {
  transform: scale(1.12);
}

/* 余额显示样式 */
.balance-row {
  display: flex;
  align-items: center;
  margin-top: 8px;
  margin-left: 12px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 12px;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.balance-label {
  font-size: 0.9rem;
  color: rgba(255, 255, 255, 0.9);
  margin-right: 8px;
}

.balance-amount {
  font-size: 1.1rem;
  font-weight: bold;
  color: #fff;
  margin-right: 12px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.recharge-btn {
  font-size: 0.85rem;
  color: #007AFF;
  background: rgba(255, 255, 255, 0.2);
  padding: 4px 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid rgba(0, 122, 255, 0.3);
}

.recharge-btn:hover {
  background: rgba(0, 122, 255, 0.2);
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.2);
}

.recharge-btn:active {
  transform: translateY(0);
}
</style>